
const state = {
    cartList: uni.getStorageSync('cartList') || []
}
const mutations = {
    cartAdd(state, payload) {
        const index = state.cartList.findIndex(goods => goods.goods_id === payload.goods_id)
        if (index === -1) {
            state.cartList.push({ ...payload, num: 1, checked: true })
        } else {
            state.cartList[index].num++
        }
        uni.setStorageSync('cartList', state.cartList)
    },
    changChecked(state, payload) {
        const index = state.cartList.findIndex(goods => goods.goods_id === payload)
        state.cartList[index].checked = !state.cartList[index].checked
        uni.setStorageSync('cartList', state.cartList)
    },
    cartNumUpdate(state, payload) {

        const index = state.cartList.findIndex(goods => goods.goods_id === payload.goods_id)

        state.cartList[index].num += payload.unit
        uni.setStorageSync('cartList', state.cartList)

    },
    delCart(state,payload){
        const index = state.cartList.findIndex(goods => goods.goods_id === payload.goods_id)
        state.cartList.splice(index,1)
        uni.setStorageSync('cartList', state.cartList)
    },
    allCheckedToggle(state,payload){
        state.cartList.forEach(item => {
            item.checked = payload.value
        });
    }
}
const getters = {
    cartCount(state) {
        let count = 0
        state.cartList.forEach(item => {
            count += item.num
        });
        return count
    },
    isAllChecked(state) {
        return state.cartList.length && state.cartList.every(item => item.checked)
    },

     checkList(state){
        return state.cartList.filter(item => item.checked === true)
     },

    cartTotal(state,getters){
        let total = 0
        getters.checkList.forEach(item => {
            total += item.num
        })
        return total
    },
    priceTotal(state,getters){
        let total = 0
        getters.checkList.forEach(item => {
            total += item.num * item.goods_price
        })
        return total
    }
}
const actions = {

}

export default {
    namespaced: true,
    state,
    mutations,
    getters,
    actions
}